package cn.dongqihong.framework.util;

import java.math.BigDecimal;

/**
 * 双精度计算工具
 * Created by DongQihong on 2017/5/5.
 */
public class DoubleComputeUtil {
    /**
     * 工具类不用实例化
     */
    private DoubleComputeUtil() {

    }

    /**
     * 加
     *
     * @param v1
     * @param v2
     * @return {@code v1 + v2}
     */
    public static BigDecimal add(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2);
    }

    /**
     * 减
     *
     * @param v1 被减数
     * @param v2 减数
     * @return {@code v1 - v2}
     */
    public static BigDecimal sub(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.subtract(b2);
    }


    /**
     * 乘
     *
     * @param v1
     * @param v2
     * @return {@code v1 * v2}
     */
    public static BigDecimal mul(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.multiply(b2);
    }

    /**
     * 除，默认使用四舍五入，保留两位小数
     *
     * @param v1 被除数
     * @param v2 除数
     * @return {@code v1 / v2}
     */
    public static BigDecimal div(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2, 2, BigDecimal.ROUND_HALF_UP);//四舍五入,保留2位小数
    }

    /**
     * 除
     *
     * @param v1           被除数
     * @param v2           除数
     * @param scale        保留位数
     * @param roundingMode 保留模式
     * @return {@code v1 / v2}
     * @see java.math.BigDecimal#divide
     * @see java.math.BigDecimal#ROUND_UP
     * @see java.math.BigDecimal#ROUND_DOWN
     * @see java.math.BigDecimal#ROUND_CEILING
     * @see java.math.BigDecimal#ROUND_FLOOR
     * @see java.math.BigDecimal#ROUND_HALF_UP
     * @see java.math.BigDecimal#ROUND_HALF_DOWN
     * @see java.math.BigDecimal#ROUND_HALF_EVEN
     * @see java.math.BigDecimal#ROUND_UNNECESSARY
     */
    public static BigDecimal div(double v1, double v2, int scale,
                                 int roundingMode) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2, scale, roundingMode);//四舍五入,保留2位小数
    }

}
